<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	
	var $components = array('Auth', 'Session');
	
	public $helpers = array('Cache');
	
	public function beforeFilter(){
	    
		$site_desktop = 'http://demo.cheenyu.com/cake_ticket/';
		$site_wechat = 'http://demo.cheenyu.com/cake_ticket/Index/wechat';
		$site_h5 = 'http://m.cheenyu.com/cake_ticket/';
		
		$this->Auth->flash = array('element' => 'tip/tip','params'=>'','key' => 'auth');
		$this->Auth->authError = "对不起,您没有认证权限";
		$this->Auth->loginAction = array('plugin'=>false,'admin'=>false,'controller' => 'Index', 'action' => 'index');
		$this->Auth->logoutRedirect = array('plugin'=>false,'admin'=>false,'controller' => 'Index', 'action' => 'index');
		$this->Auth->autoRedirect = false;
		
		$this->Auth->allow('CakeError');
		
		$visitor = Router::url('/',true);
		if(!in_array($visitor, array(
		    $site_desktop,
		    $site_h5
		))){
		    return $this->redirect($site_desktop);
		}
		
		$user_agent = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
		$in_wechat = !(strpos($user_agent, 'MicroMessenger') === false);
		if($this->request->is('mobile') || $in_wechat){ 
			if(Router::url('/',true)==$site_h5){
				if($this->here == '/'){
					$this->redirect($site_wechat);
				}
				$this->theme = 'Wechat';
			}else{
			    $ext_url = substr(str_replace('/', '_',$this->here),1);
				$this->redirect($site_h5.$ext_url);
			}
		}else{
		    //echo Router::url('/',true);
			if(Router::url('/',true)==$site_h5){
				if($this->here == '/'||($this->name == 'Index' && $this->action == 'wechat')){
					$this->redirect($site_desktop);
				}else if(in_array($this->name, array('Tickets'))){
					$ext_url = substr(str_replace('/', '_',$this->here),1);
					$this->redirect($site_desktop.$ext_url);
				}
				
				$this->theme = 'Wechat';
			}
		}
		 
		if($this->theme == 'Wechat'){
			if (!$in_wechat) {
				// 非微信浏览器禁止浏览
				if (!$this->Auth->user() 
						&& (($this->name == 'UserOrders' && $this->action == 'add') 
							|| ($this->name == 'Users' && $this->action == 'index'))){
					$ext_url = substr(str_replace('/', '_',$this->here),1);
					$this->Session->write('wxjump',Router::url('/',true).$ext_url);
					$this->redirect(array('plugin'=>false,'controller'=>'Users','action'=>'login'));
				}
			} else {
				if (!$this->Auth->user() && !in_array($this->action, array('bind','valid','payback'))) {
					$ext_url = substr(str_replace('/', '_',$this->here),1);
					$this->Session->write('wxjump',Router::url('/',true).$ext_url);
					$this->redirect(array('plugin'=>'wechat','controller'=>'WxUser','action'=>'bind'));
				}
			}
		}
		
		if (!empty($this->params['prefix']) && $this->params['prefix'] == 'admin') {
			$this->Auth->loginAction = array('plugin'=>false,'admin'=>true,'controller' => 'Users', 'action' => 'login');
			$this->Auth->logoutRedirect = array('plugin'=>false,'admin'=>true,'controller' => 'Users', 'action' => 'login');
			$this->layout = 'admin';
			$this->locateMenu();
			$this->SysWebsite();
		}else{
			$this->Auth->flash = array('element' => 'tip/tip_uc','params'=>'','key' => 'auth');
			if(!isset($this->request->params['city'])) $this->request->params['city'] = 'sh';
			Configure::write('CITYSIGN', $this->request->params['city']);
			$this->set('CITYSIGN',$this->request->params['city']);
			$this->site_switch();
			$this->site_fonts();
			Configure::write('SITEID', $this->site_id());
			$this->setting();
			$this->keywords($this->site_id());
			$this->seourl($this->site_id());
			//pr($this->request->url()); exit;
		}
		$this->Auth->authorize = array(
				'Controller',
				'Actions' => array('actionPath' => 'controllers')
		);
		if ($this->Auth->loggedIn()) {
			$this->set('Auth',$this->Auth->user());
		}else{
			if ($this->request->isAjax() && !in_array($this->action,$this->Auth->allowedActions)) {
				$fbd = array('state'=>false,'msg'=>'您长时间没有操作，请重新登录');
				echo json_encode($fbd);
				exit;
			}
		}
		if ($this->request->isAjax() && $this->theme != 'Wechat') {
			
        	$this->layout = 'ajax';
        }
        
        if($this->name == 'CakeError'){
        	//$this->layout = 'user';
        }
	}
	
	function isAuthorized() {
		return $this->Auth->loggedIn();
	}
	
	/**
	 * locate menu and get bread
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午3:22:36
	 * @param variable
	 * @return 
	 */
	public function locateMenu(){
		$bread = array();
		if(CakePlugin::loaded("Menu")){
			$this->loadModel('Menu.Menu');
			$locate = $this->Menu->getTreePoint($this->name,$this->action);
			if($locate && $locate['Menu']['parent_id']>1){
				$bread = $this->Menu->getBread($locate['Menu']['parent_id']);
			}
			$bread[4] = $locate;
		}else{
			$locate = false;
		}
		$this->set('_bread',$bread);
		$this->set('locate',$locate);
	}
	
	/**
	 * 站群缓存
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午12:45:38
	 * @param variable
	 * @return 
	 */
	public function SysWebsite(){
		$SysWebSite = Cache::read('sys_website_cache', '_zmx_month_cache_');
		if(!$SysWebSite){
			$this->loadModel('SysWebsite');
			$SysWebSite = $this->SysWebsite->getEanbleSite();
			Cache::write('sys_website_cache', $SysWebSite, '_zmx_month_cache_');
		}
		$this->set('SysWebsite',$SysWebSite);
	}
	
	/**
	 * 系统设置
	 * @param unknown_type $return
	 * @return mixed
	 */
	public function setting($return = false){
		$SITEID = 1;//Configure::read('SITEID');
		$setting = Cache::read('sys_setting_'.$SITEID, '_zmx_month_cache_');
		if(!$setting){
			$file = new File(TMP.DS.'cache'.DS.'config'.$SITEID);
			$setting = unserialize($file->read());
			Cache::write('sys_setting_'.$SITEID, $setting, '_zmx_month_cache_');
		}
		
		if($return){
			return $setting;
		}else{
			$this->set('seo_title',$setting['Setting']['site_title']);
			$this->set('seo_keywords',$setting['Setting']['site_keywords']);
			$this->set('seo_description',$setting['Setting']['site_description']);
			$this->set('setting',$setting);
		}
	}
	
	public function site_fonts(){
		$sign = Configure::read('CITYSIGN'); 
		$site_fonts = Cache::read('nav_cache_'.$sign, '_zmx_month_cache_');
		if(!$site_fonts){
			$siteid = $this->site_id();
			$this->loadModel('SysFront');
			$site_fonts = $this->SysFront->getSysFont($siteid);
			Cache::write('nav_cache_'.$sign, $site_fonts, '_zmx_month_cache_');
		}
		$this->set('site_fronts',$site_fonts);
	}
	
	public function site_id(){
		$sign = Configure::read('CITYSIGN');
		$site = ($this->site_switch(true));
		foreach ($site as $s){
			if($s['SysWebsite']['sign'] == $sign){
				return $siteid = $s['SysWebsite']['id'];
				break;
			}
		}
	}
	
	public function site_switch($return = false){
		$switch_cache = Cache::read('switch_cache', '_zmx_month_cache_');
		if(!$switch_cache){
			$this->loadModel('SysWebsite');
			$switch_cache = $this->SysWebsite->getSwitchSite();
			Cache::write('switch_cache', $switch_cache, '_zmx_month_cache_');
		}
		if($return){
			return $switch_cache;
		}else{
			$this->set('switch_cache',$switch_cache);
		}
	}
	
	function keywords(){
		$this->loadModel('SysSearch');
		$hotKey = $this->SysSearch->find('list',array(
			'fields'=>array('SysSearch.key'),
			'order'=>'SysSearch.sort_top DESC,SysSearch.times DESC',
			'limit'=>5
		));
		$this->set('hotKey',$hotKey);
	}
	
	function seourl($site_id){
		$this->loadModel('TicketCate');
		$seoTC = $this->TicketCate->find('list',array(
				'fields'=>array('TicketCate.id','TicketCate.title_en'),
				'conditions'=>array(
						'TicketCate.id >' =>1,
						'TicketCate.sys_website_id'=>$site_id
				)
		));
		$this->set('seoTC',$seoTC);
		return $seoTC;
	}
	
	function decodeseourl(){
		
	}
	
}